<template>
  <a-modal
    width="800px"
    v-model="showAddressModal"
    destroyOnClose
    centered
    title="拖动或搜索进行地图定位"
    @ok="submitOk"
    @cancel="cancel"
  >
    <template #closeIcon>
      <section class="mt-10 mr-20 flex items-start justify-end px-4 pt-8">
        <a-icon type="close"/>
      </section>
    </template>
    <div class="mb-10 flex relative" style="z-index: 2">
      <a-input placeholder="请输入地址搜索定位" class="w-400" v-model="address" allowClear @change="searchHandle"/>
      <div class="w-full absolute top-0 mt-40 ss-serach-box px-10 bg-white search"
           v-if="isShowSearchList&&searchList.length>0">
        <div class="relative py-15 text-12 relative b-line cursor-pointer" v-for="(item, index) in searchList"
             :key="index" @click="serchItemClickHandle(item)">{{ item.name }}{{ item.address }}
        </div>
      </div>
    </div>
    <div ref="map" style="position: relative;height: 400px;z-index: 1"/>
  </a-modal>
</template>
<script>
import AMap from 'AMap'

export default {
  name: 'AddressComp',
  data() {
    return {
      showAddressModal: false,
      aMap: null,
      pin: require('@/assets/icons/pin.png'),
      address: null,
      marker: null,
      data: null,
      type: 0,
      searchList: [],
      placeSearch: null,
      isShowSearchList: false
    }
  },
  props: {
    city: { // 当前搜索的城市
      type: String,
      default() {
        return ''
      }
    }
  },
  methods: {
    serchItemClickHandle(e) { // 地图点击
      const {lng, lat} = e.location
      this.address = e.address
      this.aMap.setCenter([lng, lat])
      this.data = {...this.data, address: e.address, longitude: lng, latitude: lat}
      this.isShowSearchList = false
    },
    searchHandle() { // 地图搜索
      this.placeSearch.search(this.address, (status, result) => {
        if (status == 'complete') {
          this.searchList = result.poiList.pois
          this.isShowSearchList = true
        }
      })
    },
    submitOk() {
      if (!this.data) return this.$message.warning('请选择地址')
      this.$emit('uploadPoint', {...this.data, type: this.type})
      this.cancel()
    },
    cancel() {
      this.data = null
      this.aMap = null
      this.isShowSearchList = false
      this.showAddressModal = false
    },
    setMapPoint(data) {
      const {longitude, latitude, address} = data
      if (this.marker) this.aMap.remove(this.marker)
      this.$nextTick(() => {
        const position = [longitude, latitude]
        this.aMap.setCenter(position, true, 0)
        this.marker = new AMap.Marker({
          position,
          icon: this.pin,
          offset: new AMap.Pixel(0, 0),
          draggable: true,
          cursor: 'move',
          // 设置拖拽效果
          raiseOnDrag: true
        })
        // this.marker.on('dragend', showInfoDragend)
        this.marker.setMap(this.aMap)
        this.marker.on('dragend', this.showInfoDragend)
        this.marker.setLabel({
          direction: 'top',
          offset: new AMap.Pixel(0, -10),
          content: address
        })
        this.data = data
      })
    },
    showInfoDragend(e) {
      const {lng, lat} = e.lnglat
      this.getAddress([lng, lat])
      console.log('拖拽', e.lnglat);
    },
    showInfoClick(e) {
      const lng = e.lnglat.getLng()
      const lat = e.lnglat.getLat()
      this.getAddress([lng, lat])
      if (e.keyCode === 13) {
        regeoCode()
        return false
      }
      return true
    },
    //根据经纬度获取地址
    getAddress(data) {
      this.geocoder.getAddress(data, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          this.address = result.regeocode.formattedAddress
          this.setMapPoint({address: this.address, longitude: data[0], latitude: data[1]})
        } else {
          console.error('根据经纬度查询地址失败')
        }
      })
    },
    // 获取搜索信息
    getAddressValue(data) {
      console.log('data', data);
      const {address, type, longitude, latitude} = data
      if (type) this.type = type
      this.address = address
      this.showAddressModal = true
      this.$nextTick(() => {
        if (!this.aMap) {
          AMapUI.loadUI(['misc/PositionPicker'], (PositionPicker) => {
            this.aMap = new AMap.Map(this.$refs.map, {
              zoom: 16,
              center: longitude ? [longitude, latitude] : undefined
            })
            AMap.plugin('AMap.PlaceSearch', () => {
              this.placeSearch = new AMap.PlaceSearch({
                pageSize: 100,
                city: this.city
              })
            })
            if (!longitude) {
              AMap.plugin('AMap.Geolocation', () => {
                let geolocation = new AMap.Geolocation({
                  enableHighAccuracy: true,//是否使用高精度定位，默认:true
                  timeout: 10000,          //超过10秒后停止定位，默认：5s
                  buttonPosition: 'RB',    //定位按钮的停靠位置
                  buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                  zoomToAccuracy: true   //定位成功后是否自动调整地图视野到定位点
                })
                this.aMap.addControl(geolocation)
                geolocation.getCurrentPosition(function (status, result) {
                  if (status == 'complete') {
                    onComplete(result)
                  } else {
                    onError(result)
                  }
                })
              })
              //解析定位结果
              const onComplete = (data) => {
                const {lng, lat} = data.position
                this.aMap.setCenter([lng, lat])
              }
              //解析定位错误信息
              const onError = (data) => {
                this.$message.warning('自动定位失败，请点击地图选择')
              }
            }
            this.positionPicker = new PositionPicker({
              mode: 'dragMap',
              map: this.aMap,
              iconStyle: {//自定义外观
                url: this.pin,//图片地址
                size: [32, 32],  //要显示的点大小，将缩放图片
                ancher: [24, 40],//锚点的位置，即被size缩放之后，图片的什么位置作为选中的位置
              }
            })
            this.positionPicker.on('success', (positionResult) => {
              const {lng, lat} = positionResult.position
              const address = positionResult.address
              this.data = {...this.data, address, longitude: lng, latitude: lat}
              this.address = address
            })
            this.positionPicker.on('fail', function (positionResult) {
            })
            this.positionPicker.start()
          })
        }
      })
    }
  }
}
</script>
<style scoped lang="less">
/deep/ .amap-markers {
  .amap-icon {
    img {
      width: 25px;
      height: 25px;
    }
  }

  .amap-marker-label {
    position: absolute;
    z-index: 2;
    border: none;
    background-color: #fff;
    white-space: nowrap;
    cursor: default;
    padding: 10px 12px;
    font-size: 14px;
    line-height: 14px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, .15);
    border-radius: .25rem;
  }
}

.search {
  max-height: 475px;
  overflow: auto;
}
</style>
